package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.ConfirmAnOrderResponse
import com.gexiaobao.pigeon.app.model.param.AddOrReGoodsParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.FragmentOrderFinishBinding
import com.gexiaobao.pigeon.ui.adapter.ConfirmOrderAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/7/4 16:06
 * @Describe    : 确认订单（完成之后）
 */
class FragmentConfirmOrderFinish : BaseFragment<MallViewModel, FragmentOrderFinishBinding>() {

    private val mAdapter: ConfirmOrderAdapter by lazy { ConfirmOrderAdapter(arrayListOf()) }
    private var id = ""
    private lateinit var dialog: RxDialogDefault//删除订单弹窗

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        id = arguments?.getString("orderId").toString()//170
        mDatabind.recyclerViewOrderDetail.init(LinearLayoutManager(context), mAdapter)
        mDatabind.recyclerViewOrderDetail.adapter = mAdapter

        /** 监听物理返回键 */
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    val type = arguments?.getString("type").toString()
                    if (type == "1") {
                        nav().navigateUp()
                    } else {
                        nav().popBackStack(R.id.fragmentConfirmOrderProgress, true)
                    }
                }
            })

        mAdapter.setOnReturnGoodsClickListener(object : ConfirmOrderAdapter.OnBtnReturnClickListener {
            override fun onBtnReturnClick(position: Int, goodsId: Int, orderId: Int, orderStatus: Int, shopId: Int, shopOrderId: Int) {
                when (orderStatus) {
                    3, 4 -> {//已签收
                        nav().navigateAction(R.id.action_to_fragment_return_of_goods, Bundle().apply {
                            putInt("orderId", orderId)
                            putInt("shopUserId", shopId)
                            putString("goodsId", goodsId.toString())
                        })
                    }

                    11, 13, 14 -> {//退货详情
                        nav().navigateAction(R.id.action_to_fragment_return_detail, Bundle().apply {
                            putInt("orderId", orderId)
                            putInt("shopId", shopId)
                            putString("goodsId", goodsId.toString())
                        })
                    }

                    15 -> {//退货审核通过
                        nav().navigateAction(R.id.action_to_fragment_send_goods_out, Bundle().apply {
                            putInt("orderId", shopOrderId)
                            putInt("shopId", shopId)
                            putInt("childOrderId", orderId)
                        })
                    }
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        onRefresh()
    }

    override fun createObserver() {
        super.createObserver()
        /** 删除订单  */
        mViewModel.deleteOrderResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                dialog.dismiss()
                eventViewModel.toRefreshListShopOrder.value = true
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取订单详情  */
        mViewModel.orderDetailResult.observe(viewLifecycleOwner) {
            if (it != null) {
                dismissLoadingAntiShake()
                refreshUIData(it)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivBack,
            mDatabind.shopOrderConfirmAgainBuy,
            mDatabind.shopOrderConfirmDel
        ) {
            when (it) {
                mDatabind.ivBack -> {
                    val type = arguments?.getString("type").toString()
                    if (type == "1") {
                        nav().navigateUp()
                    } else {
                        nav().popBackStack(R.id.fragmentConfirmOrderProgress, true)
                    }
                }

                mDatabind.shopOrderConfirmAgainBuy -> {//再次购买

                }

                mDatabind.shopOrderConfirmDel -> {//删除订单
                    delOrder()
                }
            }
        }
    }

    private fun delOrder() {
        dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.market_shop_order_sure_activity_sure_to_delete_order))
        dialog.setSureListener {
            showLoadingAntiShake(getString(R.string.loading))
            val body = AddOrReGoodsParam(id = id.toInt())
            mViewModel.userDeleteOrder(body)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun onRefresh() {
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.getShopOrderList(id)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshUIData(it: ConfirmAnOrderResponse) {
        mDatabind.tvOrderDetailTotalExpressFee.text = if (it.totalExpressFee == 0.0) {
            "免邮"
        } else {
            "¥" + it.totalExpressFee.toString()
        }
        SettingUtil.setPrice(it.finalPrice.toString(), mDatabind.tvOrderDetailFinalPrice, 60, Color.BLACK)
        mDatabind.data = it
        if (!it.isEmpty()) {
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
        }
    }
}